﻿#include "Serial.h"

CSerial::CSerial(QObject *parent) :QObject(parent),m_pSerial(NULL)
{
}

CSerial::~CSerial()
{    //关闭串口
    CloseSerial();
}

bool CSerial::OpenSerial(quint8 portNumber,QIODevice::OpenModeFlag openMode)
{
	if (m_pSerial && m_pSerial->isOpen())
	{
		return true;
	}
    m_pSerial = new QextSerialPort(QSerialPortName(portNumber));
    m_pSerial->setBaudRate(m_seialPortAttribute.baudRate);
    m_pSerial->setDataBits(m_seialPortAttribute.dataBit);
    m_pSerial->setParity(m_seialPortAttribute.parity);
    m_pSerial->setStopBits(m_seialPortAttribute.stopBit);
    m_pSerial->setFlowControl(FLOW_OFF);
    connect(m_pSerial,SIGNAL(readyRead()),this,SIGNAL(ReadSerial()));
	if (!m_pSerial->open(QIODevice::ReadWrite))
	{
		return false;
	}
    return true;
}
/*
 *关闭串口
*/
void CSerial::CloseSerial()
{
    if(m_pSerial != NULL){
        if(m_pSerial->isOpen()){
            m_pSerial->close();
        }
        delete m_pSerial;
        m_pSerial = NULL;
    }
}

//void CSerial::ReadSerial()
//{
//	char ch[256] = {0};
//	int len = m_pSerial->read(ch,256);
//	SendData(ch,len);
//}

void CSerial::SendData( const char* data, quint64 len )
{
	if (m_pSerial->isOpen())
	{	
		m_pSerial->write(data,len);
	}
}

void CSerial::SendData(QByteArray _data)
{
	m_pSerial->write(_data);
}

